package com.wyl.studyredis.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyl.studyredis.business.entity.School;
import com.wyl.studyredis.business.mapper.SchoolMapper;
import com.wyl.studyredis.business.service.ISchoolService;
import com.wyl.studyredis.business.service.IStudentService;
import com.wyl.studyredis.business.util._CacheKeyUtil;
import com.wyl.studyredis.business.vo.SchoolVo;
import com.wyl.studyredis.business.vo.StudentVo;
import com.wyl.studyredis.framework.util._BeanUtil;
import com.wyl.studyredis.framework.util._SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyl
 * @since 2022-02-11
 */
@Service("schoolService")
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements ISchoolService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    @Lazy // 解决循环依赖问题
    private IStudentService studentService;

    @Override
    public SchoolVo getSchoolVoByIdInCache(String id, boolean isDeep) throws Exception {
        //1.根据入参id，匹配"school:id"，找到school（走缓存）
        ISchoolService _this = _SpringContextUtil.getBean(ISchoolService.class);
        School school = _this.getSchoolById(id);
        if(null == school){
            return null;
        }
        SchoolVo schoolVo = _BeanUtil.copyProperties(school, SchoolVo.class);

        if(isDeep){
            // 2.根据school:id:student，找到关联的studentId（走缓存）
            String schoolStudentKey = _CacheKeyUtil.getSchoolStudentKey(school.getId());
            List<String> studentIds = ObjectUtil.defaultIfNull(
                    stringRedisTemplate.opsForList().range(schoolStudentKey, 0, -1),
                    new ArrayList<>(0));
            // 3.根据studentId，找到student（走缓存）
            List<StudentVo> studentVoList = new ArrayList<>(studentIds.size());
            for (String studentId : studentIds) {
                StudentVo studentVo = studentService.getStudentVoByIdInCache(studentId, false);
                studentVoList.add(studentVo);
            }
            // 4.构造Vo返回值（vo不缓存起来）
            schoolVo.setStudentList(studentVoList);
        }
        return schoolVo;
    }

    @CachePut(cacheNames = School.cacheName, key = "#result.id")
    @Override
    public School saveAndCache(School school) {
        // 1.保存school，并且更新到"school::id"
        super.save(school);
        return school;
    }

    @CachePut(cacheNames = School.cacheName, key = "#result.id")
    @Override
    public School updateByIdAndCache(School school) {
        // 1.保存school，并且更新到"school::id"
        super.save(school);
        return school;
    }

    @CacheEvict(cacheNames = School.cacheName, key = "#id")
    @Transactional
    @Override
    public void removeByIdAndCache(String id) {
        // 删除school，并且删除"school::id"
        super.removeById(id);
        // 删除school关联的学生
//        studentService.remove()

        // 删除"school::id::student"
        stringRedisTemplate.delete(_CacheKeyUtil.getSchoolStudentKey(id));
    }

    // cacheable放在子方法不生效，类似@Transational
    // 解决方法：https://www.cnblogs.com/cyhbyw/p/8615816.html、https://blog.csdn.net/qq_36990177/article/details/109755106?utm_source=app&app_version=5.0.0
    @Cacheable(cacheNames = School.cacheName, key = "#id")
    @Override
    public School getSchoolById(String id) {
        return super.getById(id);
    }

}
